import Vue from 'vue'
import VueI18n from 'vue-i18n'
const defaultLang = 'es'

Vue.use(VueI18n)

export let lang = defaultLang
if (navigator.userAgent.indexOf('umoocApp') !== -1) {
  var ua =
    window.navigator.userAgent.indexOf('-language-') != -1
      ? window.navigator.userAgent
      : ''
  var start = ua.indexOf('-language-') + '-language-'.length
  var end = ua.indexOf(' ', start)
  end = end == -1 ? ua.length : end

  try {
    lang =
      ua.substring(start, end) ||
      navigator.language ||
      navigator.browserLanguage
  } catch (e) {
    lang = navigator.language || navigator.browserLanguage
  }
}
lang = lang.toLowerCase()
const langMap = {
  tw: ['tw', 'hk'],
  en: ['en'],
  th: ['th'],
  es: ['es'],
  ar: ['ar'],
  id: ['id'],
  zh: ['zh']
}
let langKey = defaultLang
for(let key in langMap) {
  const arr = langMap[key].filter(it => lang.indexOf(it) !== -1)
  if (arr.length > 0) {
    langKey = key
    break
  }
}
lang = langKey

const vueI18nMap = {
  zh: 'zh-CN',
  tw: 'zh_TW'
}
document.documentElement.setAttribute('lang', vueI18nMap[lang] || lang)
if (lang === 'ar') {
  document.documentElement.setAttribute('dir', 'rtl')
}

const i18n = new VueI18n({
  locale: lang,
  fallbackLocale: defaultLang || 'zh'
})

const msg = require(`./lang/${lang}.json`)
i18n.setLocaleMessage(lang, {msg})

export default i18n
